import { apiUrl } from '../config/config';
import errorCode from './errorCode';
import {
  toast,
  tansParams,
} from './common';

const requestObj = {};

let timeout = 10000;

const requestFinish = ({ timeStr }) => {
  delete requestObj[ `time${timeStr}` ];
  if (!Object.keys(requestObj).length) {
    uni.hideLoading();
  }
};

const request = (config, timeStr) => {
  timeStr = timeStr || new Date().valueOf();
  
  // 是否需要设置 token
  // const isToken = (config.headers || {}).isToken === false || config.unCheckToken;
  // config.header = config.header || {};
  // if (getToken() && !isToken) {
  //   config.header[ 'Authorization' ] = 'Bearer ' + getToken();
  // }
  // get请求映射params参数
  if (config.params) {
    let url = config.url + '?' + tansParams(config.params);
    url = url.slice(0, -1);
    config.url = url;
  }
  if (!Object.keys(requestObj).length) {
    uni.showLoading({
      mask: true,
    });
  }
  requestObj[ `time${timeStr}` ] = config;
  return new Promise((resolve, reject) => {
    uni.request({
      method: config.method || 'get',
      timeout: config.timeout || timeout,
      url: config.baseUrl || apiUrl + config.url,
      data: config.data,
      header: config.header,
      dataType: 'json',
    }).then(response => {
      requestFinish({ timeStr });
      console.log(response, 123);
      const res = response;
      if (res.errMsg !== 'request:ok') {
        toast('后端接口连接异常');
        reject('后端接口连接异常');
        return;
      }
      const code = res.data.code || 200;
      const msg = errorCode[ code ] || res.data.msg || errorCode[ 'default' ];
      if (code === 401) {
        removeToken();
      } else if (code === 500) {
        toast(msg);
        reject('500');
      } else if (code !== 200) {
        toast(msg);
        reject(code);
      }
      resolve(res.data);
    }).catch(error => {
      requestFinish({ timeStr });
      let message = error.message || error.errMsg;
      if (message === 'Network Error') {
        message = '后端接口连接异常';
      } else if (message.includes('timeout')) {
        message = '系统接口请求超时';
      } else if (message.includes('Request failed with status code')) {
        message = '系统接口' + message.substr(message.length - 3) + '异常';
      }
      toast(message);
      reject(error);
    });
  });
};

export const myAjax = async (url, params, options = {}) => {
  const method = options.method || 'get';
  if (method === 'get' && params) {
    url = url + '?' + tansParams(params);
    url = url.slice(0, -1);
  }
  const config = {
    url,
    method,
    data: params,
  };
  return request(config);
};

export default {
  request,
  myAjax,
};
